"""
检验单查询服务
"""
import random
import logging
from datetime import datetime, timedelta
from config import get_config

config = get_config()
logger = logging.getLogger(__name__)


class InspectionService:
    """检验单查询服务类"""

    # 检验类型
    INSPECTION_TYPES = [
        {"code": "LLCheckApply", "name": "来料检验", "category": "来料"},
        {"code": "PRODCheckApply", "name": "生产检验", "category": "生产"},
        {"code": "FINCheckApply", "name": "成品检验", "category": "成品"},
        {"code": "IPQCCheckApply", "name": "过程检验", "category": "生产过程"}
    ]

    # 检验状态
    INSPECTION_STATUS = [
        {"code": "PENDING", "name": "待检验", "value": "0"},
        {"code": "IN_PROGRESS", "name": "检验中", "value": "3"},
        {"code": "COMPLETED", "name": "已完成", "value": "1"},
        {"code": "FAILED", "name": "检验不合格", "value": "2"},
        {"code": "CANCELLED", "name": "已取消", "value": "4"}
    ]

    # 检验中心
    INSPECTION_CENTERS = [
        {"id": "1503239447124639752", "code": "QC001", "name": "来料检验中心"},
        {"id": "1503239447124639753", "code": "QC002", "name": "生产过程检验中心"},
        {"id": "1503239447124639754", "code": "QC003", "name": "成品检验中心"},
        {"id": "1503239447124639755", "code": "QC004", "name": "出厂检验中心"}
    ]

    @staticmethod
    def query_inspection_list(query_data: dict) -> dict:
        """检验申请列表查询"""
        # 解析查询参数
        page_index = query_data.get('pageIndex', 1)
        page_size = query_data.get('pageSize', 10)
        status = query_data.get('status', '')
        code = query_data.get('code', '')
        product = query_data.get('product', '')
        batch_num = query_data.get('batchNum', '')
        inspection_center = query_data.get('qualityinSpectionCenter', '')
        check_org = query_data.get('checkOrg', '')
        check_dept = query_data.get('checkDept', '')
        check_people = query_data.get('checkPeople', '')

        # 生成总的检验单数据
        total_count = 38
        all_inspections = InspectionService._generate_inspection_data(total_count)

        # 根据查询条件过滤
        filtered_inspections = []
        for inspection in all_inspections:
            # 状态过滤
            if status and inspection.get('status') != status:
                continue

            # 单据编码过滤
            if code and code not in inspection.get('inspection_code', ''):
                continue

            # 物料过滤
            if product and product not in inspection.get('material_code', ''):
                continue

            # 批次号过滤
            if batch_num and batch_num not in inspection.get('batch_num', ''):
                continue

            # 检验中心过滤
            if inspection_center and inspection_center not in inspection.get('org_code', ''):
                continue

            # 请检组织过滤
            if check_org and check_org not in inspection.get('check_org', ''):
                continue

            # 请检部门过滤
            if check_dept and check_dept not in inspection.get('check_dept', ''):
                continue

            # 请检人员过滤
            if check_people and check_people not in inspection.get('check_people', ''):
                continue

            filtered_inspections.append(inspection)

        # 分页处理
        total_filtered = len(filtered_inspections)
        start_idx = (page_index - 1) * page_size
        end_idx = min(start_idx + page_size, total_filtered)

        page_items = filtered_inspections[start_idx:end_idx]

        # 计算统计信息
        stats = {
            'total': total_filtered,
            'pending': len([item for item in filtered_inspections if item.get('status') == 'PENDING']),
            'in_progress': len([item for item in filtered_inspections if item.get('status') == 'IN_PROGRESS']),
            'completed': len([item for item in filtered_inspections if item.get('status') == 'COMPLETED']),
            'failed': len([item for item in filtered_inspections if item.get('status') == 'FAILED']),
            'cancelled': len([item for item in filtered_inspections if item.get('status') == 'CANCELLED'])
        }

        logger.info(f"检验申请列表查询完成: 总记录数={total_count}, 过滤后={total_filtered}, 当前页={len(page_items)}")

        return {
            "total": total_filtered,
            "pageIndex": page_index,
            "pageSize": page_size,
            "items": page_items,
            "statistics": stats  # 新增统计信息
        }

    @staticmethod
    def query_inspection_detail(inspection_id: str = None, inspection_code: str = None, billnum: str = None) -> dict:
        """检验申请详情查询"""
        # 模拟查找检验单详情
        if inspection_code:
            # 根据编码查找
            inspection_detail = InspectionService._generate_inspection_detail(inspection_code, billnum)
        elif inspection_id:
            # 根据ID查找，生成一个对应的编码
            inspection_code = f"LLQJ{datetime.now().strftime('%Y%m%d')}{str(random.randint(1000, 9999))}"
            inspection_detail = InspectionService._generate_inspection_detail(inspection_code, billnum)
        else:
            return None

        logger.info(f"检验申请详情查询完成: code={inspection_code}, billnum={billnum}")
        return inspection_detail

    @staticmethod
    def _generate_inspection_data(count: int) -> list:
        """生成检验单列表数据"""
        inspections = []

        # 定义本地物料数据，避免依赖DataGenerator
        local_materials = [
            {"code": "TM001", "name": "无氧铜丝", "unit": "千克"},
            {"code": "TM002", "name": "铝合金丝", "unit": "千克"},
            {"code": "IM001", "name": "XLPE绝缘料", "unit": "千克"},
            {"code": "IM002", "name": "PVC绝缘料", "unit": "千克"},
            {"code": "SM001", "name": "PVC护套料", "unit": "千克"},
            {"code": "SM002", "name": "PE护套料", "unit": "千克"},
            {"code": "AM001", "name": "钢带", "unit": "千克"},
            {"code": "AM002", "name": "铝带", "unit": "千克"},
            {"code": "FM001", "name": "填充绳", "unit": "千克"},
            {"code": "BM001", "name": "缠绕带", "unit": "千克"}
        ]

        for i in range(count):
            # 生成检验单编码
            inspection_code = f"LLQJ{datetime.now().strftime('%Y%m%d')}{str(random.randint(1000, 9999))}"

            # 随机选择检验类型和状态
            inspection_type = random.choice(InspectionService.INSPECTION_TYPES)
            status_info = random.choice(InspectionService.INSPECTION_STATUS)
            inspection_center = random.choice(InspectionService.INSPECTION_CENTERS)

            # 生成物料信息 - 使用本地物料数据
            material = random.choice(local_materials)

            # 生成到货日期
            arrival_date = datetime.now() - timedelta(days=random.randint(0, 30))

            # 生成批次号
            batch_num = f"B{arrival_date.strftime('%Y%m%d')}-{str(random.randint(1, 999)).zfill(3)}"

            # 生成检验人员
            check_people_list = ["张检验", "李质检", "王技师", "赵工程师", "陈主管"]
            check_people = random.choice(check_people_list)

            # 生成仓库信息
            warehouses = ["RAW", "SEMI", "FINISHED", "QC"]
            warehouse = random.choice(warehouses)

            # 推送状态
            push_status_list = ["NONE", "PENDING", "SUCCESS", "FAILED"]
            push_status = random.choice(push_status_list)

            inspection_item = {
                "inspection_code": inspection_code,
                "inspection_type": inspection_type["name"],
                "status": status_info["code"],
                "status_name": status_info["name"],
                "material_code": material["code"],
                "material_name": material["name"],
                "arrival_date": arrival_date.strftime('%Y-%m-%dT%H:%M:%S'),
                "org_code": inspection_center["id"],
                "org_name": inspection_center["name"],
                "batch_num": batch_num,
                "check_people": check_people,
                "warehouse": warehouse,
                "push_status": push_status,
                # 额外字段
                "material_id": f"MAT{str(random.randint(100000, 999999))}",
                "quantity": random.randint(100, 5000),
                "unit": material["unit"],
                "supplier": random.choice(["供应商A", "供应商B", "供应商C", "供应商D"]),
                "check_org": "质量管理部",
                "check_dept": "来料检验科",
                "priority": random.choice(["高", "中", "低"]),
                "created_time": arrival_date.strftime('%Y-%m-%dT%H:%M:%S'),
                "expected_complete_time": (arrival_date + timedelta(days=random.randint(1, 7))).strftime('%Y-%m-%dT%H:%M:%S')
            }

            inspections.append(inspection_item)

        # 按到货日期倒序排列
        inspections.sort(key=lambda x: x['arrival_date'], reverse=True)
        return inspections

    @staticmethod
    def save_inspection_order(save_data: dict) -> dict:
        """检验单保存"""
        try:
            # 解析保存数据
            data = save_data.get('data', {})

            # 基本验证
            if not data:
                raise ValueError("保存数据不能为空")

            # 提取关键字段
            code = data.get('code', '')
            resubmit_check_key = data.get('resubmitCheckKey', '')
            trantype = data.get('trantype', '')
            trantype_code = data.get('trantypeCode', '001')
            vapplycheckcode = data.get('vapplycheckcode', '')
            inspect_date = data.get('inspectDate', '')
            pk_inspecter = data.get('pk_inspecter', '')
            destroy_simple_num = data.get('destroySimpleNum', 0)
            destroy_simple_mag_type = data.get('destroySimpleMagType', '0')
            destroy_simple_resp = data.get('destroySimpleResp', '0')

            logger.info(f"检验单保存: code={code}, vapplycheckcode={vapplycheckcode}")

            # 生成保存后的响应数据
            saved_order = {
                "id": f"INSP{str(random.randint(100000000, 999999999))}",
                "code": code or f"LLJY{datetime.now().strftime('%Y%m%d')}{str(random.randint(1000, 9999))}",
                "resubmitCheckKey": resubmit_check_key,
                "trantype": trantype,
                "trantypeCode": trantype_code,
                "vapplycheckcode": vapplycheckcode,
                "inspectDate": inspect_date or datetime.now().strftime('%Y-%m-%d'),
                "pk_inspecter": pk_inspecter,
                "destroySimpleNum": destroy_simple_num,
                "destroySimpleMagType": destroy_simple_mag_type,
                "destroySimpleResp": destroy_simple_resp,
                "status": "SAVED",
                "status_name": "已保存",
                "save_time": datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
                "operator": "系统自动",
                "success": True,
                "message": "检验单保存成功"
            }

            # 如果有关联的检验申请编码，可以添加关联信息
            if vapplycheckcode:
                saved_order["related_application"] = {
                    "code": vapplycheckcode,
                    "status": "LINKED",
                    "link_time": datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
                }

            logger.info(f"检验单保存完成: saved_id={saved_order['id']}")
            return saved_order

        except Exception as e:
            logger.error(f"检验单保存失败: {str(e)}")
            raise e

    @staticmethod
    def confirm_inspection_order(confirm_data: dict) -> dict:
        """检验单确认"""
        try:
            # 提取关键字段
            code = confirm_data.get('code', '')
            inspection_id = confirm_data.get('id', '')
            billnum = confirm_data.get('billnum', 'qms_LLCheckApply_card')
            confirm_date = confirm_data.get('confirmDate', '')

            if not code and not inspection_id:
                raise ValueError("code 或 id 至少需要提供一个")

            logger.info(f"检验单确认: code={code}, id={inspection_id}")

            # 生成确认后的响应数据
            confirmed_order = {
                "id": inspection_id or f"INSP{str(random.randint(100000000, 999999999))}",
                "code": code or f"LLJY{datetime.now().strftime('%Y%m%d')}{str(random.randint(1000, 9999))}",
                "billnum": billnum,
                "confirmDate": confirm_date or datetime.now().strftime('%Y-%m-%d'),
                "status": "CONFIRMED",
                "status_name": "已确认",
                "confirm_time": datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
                "confirmer": "系统自动",
                "success": True,
                "message": "检验单确认成功",
                # 确认相关信息
                "confirm_result": {
                    "result": "PASSED",
                    "result_name": "确认通过",
                    "confirm_id": f"CONF{str(random.randint(100000, 999999))}",
                    "remarks": "检验单确认完成，所有项目符合要求"
                },
                # 流程信息
                "workflow": {
                    "current_step": "CONFIRMED",
                    "next_step": "CLOSED",
                    "can_modify": False,
                    "can_cancel": False
                }
            }

            # 如果提供了确认日期，添加确认详情
            if confirm_date:
                confirmed_order["confirm_details"] = {
                    "scheduled_date": confirm_date,
                    "actual_date": datetime.now().strftime('%Y-%m-%d'),
                    "is_on_time": True,
                    "delay_reason": None
                }

            logger.info(f"检验单确认完成: confirmed_id={confirmed_order['id']}")
            return confirmed_order

        except Exception as e:
            logger.error(f"检验单确认失败: {str(e)}")
            raise e

    @staticmethod
    def _generate_inspection_detail(inspection_code: str, billnum: str) -> dict:
        """生成检验单详情数据"""
        # 随机选择基础信息
        inspection_type = random.choice(InspectionService.INSPECTION_TYPES)
        status_info = random.choice(InspectionService.INSPECTION_STATUS)
        inspection_center = random.choice(InspectionService.INSPECTION_CENTERS)

        # 定义本地物料数据，避免依赖DataGenerator
        local_materials = [
            {"code": "TM001", "name": "无氧铜丝", "unit": "千克"},
            {"code": "TM002", "name": "铝合金丝", "unit": "千克"},
            {"code": "IM001", "name": "XLPE绝缘料", "unit": "千克"},
            {"code": "IM002", "name": "PVC绝缘料", "unit": "千克"},
            {"code": "SM001", "name": "PVC护套料", "unit": "千克"},
            {"code": "SM002", "name": "PE护套料", "unit": "千克"},
            {"code": "AM001", "name": "钢带", "unit": "千克"},
            {"code": "AM002", "name": "铝带", "unit": "千克"},
            {"code": "FM001", "name": "填充绳", "unit": "千克"},
            {"code": "BM001", "name": "缠绕带", "unit": "千克"}
        ]

        # 生成物料信息
        material = random.choice(local_materials)

        # 生成时间信息
        arrival_date = datetime.now() - timedelta(days=random.randint(1, 15))
        create_date = arrival_date - timedelta(hours=random.randint(1, 24))

        # 生成检验项目
        inspection_items = [
            {"item": "外观检验", "result": "合格", "value": "无划伤、无变形"},
            {"item": "尺寸检验", "result": "合格", "value": "符合图纸要求"},
            {"item": "材质检验", "result": "合格", "value": "材质证明书齐全"},
            {"item": "性能检验", "result": "合格", "value": "各项指标达标"}
        ]

        # 随机选择2-4个检验项目
        selected_items = random.sample(inspection_items, random.randint(2, 4))

        # 生成附件信息
        attachments = [
            {"name": "检测报告.pdf", "url": f"https://erp.yonyoucloud.com/files/report_{inspection_code}.pdf"},
            {"name": "检测照片1.jpg", "url": f"https://erp.yonyoucloud.com/files/photo1_{inspection_code}.jpg"},
            {"name": "质量证明书.pdf", "url": f"https://erp.yonyoucloud.com/files/cert_{inspection_code}.pdf"}
        ]

        # 随机选择1-3个附件
        selected_attachments = random.sample(attachments, random.randint(1, 3))

        # 生成合格率
        qualification_rate = round(random.uniform(95.0, 99.9), 1)

        # 生成采购订单信息
        document_number = f"PO{arrival_date.strftime('%Y%m%d')}{str(random.randint(1000, 9999))}"

        return {
            "code": inspection_code,
            "billnum": billnum or "qms_LLCheckApply_card",
            "status": status_info["code"],
            "status_name": status_info["name"],
            "bustype_name": inspection_type["name"],
            "checkOrg_name": inspection_center["name"],
            "product_code": material["code"],
            "product_name": material["name"],
            "sourcebillIndex": str(random.randint(10, 99)),
            "documentNumber": document_number,
            "arrivalDate": arrival_date.strftime('%Y-%m-%d'),
            "qualificationRate": qualification_rate,
            "inspectionItems": selected_items,
            "attachments": selected_attachments,
            "remarks": f"检验批次：{arrival_date.strftime('%Y%m%d')}-{random.randint(1, 999):03d}；供应商：{random.choice(['XX材料公司', 'YY供应商', 'ZZ制造厂'])}",
            # 额外详情字段
            "quantity": random.randint(100, 5000),
            "unit": material["unit"],
            "supplier": random.choice(["供应商A", "供应商B", "供应商C"]),
            "inspector": random.choice(["张检验师", "李质检员", "王技师"]),
            "inspection_date": arrival_date.strftime('%Y-%m-%dT%H:%M:%S'),
            "completion_date": (arrival_date + timedelta(days=random.randint(1, 5))).strftime('%Y-%m-%dT%H:%M:%S') if status_info["code"] == "COMPLETED" else None,
            "warehouse_location": f"仓位-{random.randint(1, 20)}-{random.randint(1, 50):02d}",
            "batch_number": f"B{arrival_date.strftime('%Y%m%d')}-{random.randint(1, 999):03d}",
            "created_by": "系统自动",
            "created_time": create_date.strftime('%Y-%m-%dT%H:%M:%S'),
            "updated_time": datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
        }